using Admin2025.Domain.Repository;
using Admin2025.Domain.Entities;
using Admin2025.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Admin2025.Infrastructure.Repositories;

public class EfRepository<T> : IRepository<T> where T : EntityBase
{
    private readonly Admin2025DbContext _dbContext;
    private readonly DbSet<T> _dbSet;

    public EfRepository(Admin2025DbContext dbContext)
    {
        _dbContext = dbContext;
        _dbSet = dbContext.Set<T>();
    }


    public async Task<T?> GetByIdAsync(int id)
    {
        return await _dbSet.FindAsync(id);
    }
    public IQueryable<T> Table { get { return _dbSet.AsNoTracking().Where(x => x.IsDeleted == false); } }


    public async Task<IEnumerable<T>> GetAllAsync()
    {
        return await _dbSet.ToListAsync();
    }

    public async Task<T> CreateAsync(T entity)
    {
        await _dbSet.AddAsync(entity);
        await _dbContext.SaveChangesAsync();
        return entity;
    }

    public async Task UpdateAsync(T entity)
    {
        _dbSet.Update(entity);
        await _dbContext.SaveChangesAsync();
    }

    public async Task DeleteAsync(T entity)
    {
        _dbSet.Remove(entity);
        await _dbContext.SaveChangesAsync();
    }

    public Task<T?> GetByIdAsync(Guid id)
    {
        // 只查未被逻辑删除的数据
        return _dbSet.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id && x.IsDeleted == false);
    }
    public async Task<IQueryable<T>> GetPagedAsync(int pageIndex, int pageSize)
    {
        var list = await _dbSet.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
        return list.AsQueryable();
    }
}
